﻿using System;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.WebPartPages;
using System.Text;

namespace TimerWebPart
{
    public class Timer : Microsoft.SharePoint.WebPartPages.WebPart
    {
        //TODO: Change the name of the WebPart1 class to a proper name.
        //      If you change the class name of this web part you also have to
        //      update the TimerWebPart.WebPart1.webpart file in the features folder.
        //      Optionally you can change the name of the .webpart file as well, and
        //      update the webpartsmanifest.xml file accordingly.

        #region "Properties"

        private int _FontSize = 18;
        public int FontSize
        {
            get { return _FontSize; }
            set { _FontSize = value; }
        }

        private string _AlertMessage = "Please refresh your browser!";
        public string AlertMessage
        {
            get { return _AlertMessage; }
            set { _AlertMessage = value; }
        }

        private string _CountdownMessage = "Elapsed time {time} seconds";
        public string CountdownMessage
        {
            get { return _CountdownMessage; }
            set { _CountdownMessage = value; }
        }

        private string _AlertBackColor = "Red";
        public string AlertBackColor
        {
            get { return _AlertBackColor; }
            set { _AlertBackColor = value; }
        }
        private string _NormalBackColor = "Transparent";
        public string NormalBackColor
        {
            get { return _NormalBackColor; }
            set { _NormalBackColor = value; }
        }
        private string _NormalForeColor = "Black";
        public string NormalForeColor
        {
            get { return _NormalForeColor; }
            set { _NormalForeColor = value; }
        }
        private string _AlertForeColor = "Black";
        public string AlertForeColor
        {
            get { return _AlertForeColor; }
            set { _AlertForeColor = value; }
        }
        private bool _AutoRefresh = false;
        public bool AutoRefresh
        {
            get { return _AutoRefresh; }
            set { _AutoRefresh = value; } 
        }

        private int _Seconds = 10;
        public int Seconds
        {
            get { return _Seconds; }
            set {_Seconds = value; }
        }

        private bool _ShowResetButton = true;
        public bool ShowResetButton
        {
            get { return _ShowResetButton; }
            set { _ShowResetButton = value; }
        }
        #endregion

        protected override void  OnPreRender(EventArgs e)
        {

#if SHAREPOINT
            if (WebPartManager.DisplayMode == SPWebPartManager.CatalogDisplayMode
                ||
                WebPartManager.DisplayMode == SPWebPartManager.DesignDisplayMode
                ||
                WebPartManager.DisplayMode == SPWebPartManager.EditDisplayMode)

                return;
#endif

            if (!Page.ClientScript.IsClientScriptBlockRegistered("functions"))
            {
                //function scripts
                StringBuilder sbFcn = new StringBuilder();
                sbFcn.AppendLine("function resetCounter(){");
                sbFcn.AppendLine("     clearTimeout(timer_id);");
                sbFcn.AppendLine("     startCounter();");
                sbFcn.AppendLine("}");
                sbFcn.AppendLine("function startCounter(){");
                sbFcn.AppendLine("     counterTime = " + _Seconds.ToString() + ";");
                sbFcn.AppendLine("     var msg = new String('" + _CountdownMessage + "').replace(/{time}/,counterTime);");
                sbFcn.AppendLine("     changeElement('display',msg,'" + _NormalBackColor + "','" + _NormalForeColor + "','normal');");
                sbFcn.AppendLine("     timer_id = setTimeout(\"decCounter()\", 1000);");
                sbFcn.AppendLine("}");
                sbFcn.AppendLine("function changeElement(obj,text,backcolor,forecolor,fontWeight){");
                sbFcn.AppendLine("     var d = document;");
                sbFcn.AppendLine("     var dom = document.getElementById;");
                sbFcn.AppendLine("     var el = (dom)? d.getElementById(obj): d.layers[obj];");
                sbFcn.AppendLine("     if(dom){");
                sbFcn.AppendLine("         el.innerHTML = text;");    
                sbFcn.AppendLine("         el.style.fontWeight = fontWeight;");
                sbFcn.AppendLine("         el.style.backgroundColor = backcolor;");
                sbFcn.AppendLine("     }else{");
                sbFcn.AppendLine("         el.document.bgColor = backcolor;");
                sbFcn.AppendLine("         el.document.fgColor = forecolor;");
                sbFcn.AppendLine("         el.document.write(text);");
                sbFcn.AppendLine("         document.close();");
                sbFcn.AppendLine("     }");
                sbFcn.AppendLine("}");
                sbFcn.AppendLine("function decCounter(){"); 
                sbFcn.AppendLine("     counterTime -= 1;");
                sbFcn.AppendLine("     var msg;");
                sbFcn.AppendLine("     if (counterTime >= 1){");
                sbFcn.AppendLine("          msg = new String('" + _CountdownMessage + "').replace(/{time}/,counterTime);");
                sbFcn.AppendLine("          changeElement('display',msg,'" + _NormalBackColor + "','" + _NormalForeColor + "','normal');");
                sbFcn.AppendLine("          timer_id = setTimeout(\"decCounter()\", 1000);");
                sbFcn.AppendLine("     }else{");
                sbFcn.AppendLine("          clearTimeout(timer_id);");
                if (!_AutoRefresh) {
                    sbFcn.AppendLine("          msg = new String('" + _AlertMessage + "').replace(/{time}/,counterTime);");
                    sbFcn.AppendLine("          changeElement('display',msg,'" + _AlertBackColor + "','" + _AlertForeColor + "','bold');");
                }
                sbFcn.AppendLine("     }");
                sbFcn.AppendLine("}");

                Page.ClientScript.RegisterClientScriptBlock(typeof(String),
                     "functions",
                    sbFcn.ToString(),
                    true);
            }
            if (!Page.ClientScript.IsStartupScriptRegistered("startup"))
            {
                //startup script
                StringBuilder sbStart = new StringBuilder();
                sbStart.AppendLine("var counterTime;");
                sbStart.AppendLine("var timer_id;");
                sbStart.AppendLine("startCounter();");

                Page.ClientScript.RegisterStartupScript(
                        typeof(String), "startup",
                        sbStart.ToString(),
                        true);
            }

            if (this.AutoRefresh)
                {
                HtmlMeta metaRefresh = new HtmlMeta();
                metaRefresh.HttpEquiv = "Refresh";
                metaRefresh.Content = String.Format("{0}; URL={1}",
                                                    _Seconds, Page.Request.Url.ToString());
                Page.Header.Controls.Add(metaRefresh);
            }
            base.OnPreRender(e);
        }

        protected override void RenderContents(System.Web.UI.HtmlTextWriter output)
        {
#if SHAREPOINT
            if (WebPartManager.DisplayMode == SPWebPartManager.CatalogDisplayMode
                ||
                WebPartManager.DisplayMode == SPWebPartManager.DesignDisplayMode
                ||
                WebPartManager.DisplayMode == SPWebPartManager.EditDisplayMode)

                return;
#endif

            output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Id, "display");
            output.AddStyleAttribute(System.Web.UI.HtmlTextWriterStyle.FontSize, _FontSize.ToString() + "px");
            output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Span);
            output.RenderEndTag();
            output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Br);
            output.RenderEndTag();
            if (_ShowResetButton && !_AutoRefresh)
            {
                output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Id, "btnReset");
                output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Type, "button");
                output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Class, "ms-SPButton");
                output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Value, "Reset");
                output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Onclick, "resetCounter()");
                output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Input);
                output.RenderEndTag();
            }
            base.RenderContents(output);
        }

        public override ToolPart[] GetToolParts()
        {
            ToolPart[] toolparts = new ToolPart[2];
            //default tool part
            WebPartToolPart wptp = new WebPartToolPart();

            toolparts[0] = wptp;
            //custom tool parts
            toolparts[1] = new TPConfig();

            return toolparts;
        }
    }
}